package com.tpddns.flannery.cirecleoffriends.service;

import android.accessibilityservice.AccessibilityService;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.Image;
import android.media.ImageReader;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
import android.os.RecoverySystem;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.Toast;

import com.tpddns.flannery.cirecleoffriends.AppUtils;
import com.tpddns.flannery.cirecleoffriends.screenshot.FileUtil;
import com.tpddns.flannery.cirecleoffriends.screenshot.PreviewPictureActivity;
import com.tpddns.flannery.cirecleoffriends.screenshot.ScreenCaptureApplication;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

public class AccessService extends AccessibilityService {
    private static final String TAG = AccessService.class.getSimpleName();

    private ImageReader mImageReader;
    private int mScreenWidth; //屏幕宽度
    private int mScreenHeight; // 屏幕高度
    private int mScreenDensity; // 屏幕密度
    private MediaProjection mMediaProjection;
    private VirtualDisplay mVirtualDisplay;
    private static Intent mResultData = null;
    // 截图的路径
    public static String SCREENSHOTFILEPATH = "";

    @Override
    public void onAccessibilityEvent(AccessibilityEvent accessibilityEvent) {
        // 判断是否在微信朋友圈界面

        String packageName = String.valueOf(accessibilityEvent.getPackageName());
        Log.i(TAG, "packageName --> " + packageName);
        if ("com.tpddns.flannery.cirecleoffriends".equalsIgnoreCase(packageName)) {
            isThisPackageName(accessibilityEvent);
        } else if ("com.tencent.mm".equalsIgnoreCase(packageName)) {
            isWeiChatPackangeName(accessibilityEvent);
        }


    }

    @Override
    public void onInterrupt() {

    }


    //com.tpddns.flannery.cirecleoffriends
    private void isThisPackageName(AccessibilityEvent accessibilityEvent) {
        AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();// 根布局
        try {
            if (nodeInfo != null) {
                //小米
                List<AccessibilityNodeInfo> listAccNodeStartNow = nodeInfo.findAccessibilityNodeInfosByText("立即开始");
                if (listAccNodeStartNow.size() > 0) {
                    // 立即开始按钮
                    listAccNodeStartNow.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (nodeInfo != null) {
                nodeInfo.recycle();
                nodeInfo = null;
            }
        }
    }

    //com.tencent.mm
    private void isWeiChatPackangeName(AccessibilityEvent accessibilityEvent) {
        AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();// 根布局
        try {
            if (nodeInfo != null && AppUtils.IS_JUMP_FROM_ME) {
                List<AccessibilityNodeInfo> find = nodeInfo.findAccessibilityNodeInfosByText("发现");
                if (find.size() > 0 && find.get(0).getText().equals("发现")) {
                    find.get(0).getParent().performAction(AccessibilityNodeInfo.ACTION_CLICK);
                }
                List<AccessibilityNodeInfo> list = nodeInfo.findAccessibilityNodeInfosByViewId("android:id/list");
                if (list.size() > 0) {
                    list.get(0).getChild(1).performAction(AccessibilityNodeInfo.ACTION_CLICK); //跳转到微信朋友圈
                }

                //这是朋友圈
                List<AccessibilityNodeInfo> accessibilityNodeInfosByViewId = nodeInfo.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/dja");
                if (accessibilityNodeInfosByViewId.size() > 0) {
                    startScreenShot();//开始截屏
                }

                //判断朋友圈里面的内容---现在上面
                //nodeInfo.findAccessibilityNodeInfosByText("");

//                    Log.i(TAG, "获取ListView");
//                    // 获取listView
//                    List<AccessibilityNodeInfo> accessibilityNodeInfosListView = nodeInfo.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/dja");
//                    if (accessibilityNodeInfosListView.size() > 0) { //有listView
//                        AccessibilityNodeInfo accessibilityNodeInfo = accessibilityNodeInfosListView.get(0);
//                        for (int i = 0; i < accessibilityNodeInfo.getChildCount(); i++) {
//                            AccessibilityNodeInfo accessibilityNodeInfo1 = accessibilityNodeInfo.getChild(i);
//                            Rect rect = new Rect();
//                            accessibilityNodeInfo1.getBoundsInParent(rect);
//                            Log.i(TAG, "子View-->" + rect.top + " , " + rect.right + " , " + rect.bottom + " , " + rect.left);
//                        }
//                    }


//                    Log.i(TAG, "获取ListView--判断是否朋友圈的条数");
                // 获取listView-----是否
//                    if (accessibilityNodeInfosListView.size() > 0) { //有listView
//                        //List<AccessibilityNodeInfo> accessibilityNodeInfosByViewId = nodeInfo.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/dkb");
//
//
//                        AccessibilityNodeInfo accessibilityNodeInfo = accessibilityNodeInfosListView.get(0);
//                        for (int i = 0; i < accessibilityNodeInfo.getChildCount(); i++) {
//                            AccessibilityNodeInfo access = accessibilityNodeInfo.getChild(i);
//
//                            List<AccessibilityNodeInfo> accessibilityNodeInfosByViewId = access.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/dkb");
//                            if (!(accessibilityNodeInfosByViewId.size() > 0)) {
//                                Rect rect = new Rect();
//                                Log.i(TAG, "子View--头部悉尼下-->" + rect.top + " , " + rect.right + " , " + rect.bottom + " , " + rect.left);
//                                continue;
//                            }
//
//                            Rect rect = new Rect();
//                            access.getBoundsInParent(rect);
//                            Log.i(TAG, "子View-->" + rect.top + " , " + rect.right + " , " + rect.bottom + " , " + rect.left);
//                        }
//                    }

//                    //获取View---条目里面的东西
//                    List<AccessibilityNodeInfo> accessibilityNodeInfosByViewId = nodeInfo.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/dkb");
//                    if (accessibilityNodeInfosByViewId.size() > 0) {
//                        Log.i(TAG, "好多朋友圈");
//                        for (AccessibilityNodeInfo accessibilityNodeInfo : accessibilityNodeInfosByViewId) {
//                            Rect rect = new Rect();
//                            //accessibilityNodeInfo.getBoundsInParent(rect);
//                            //Log.i(TAG, "" + rect.top + " , " + rect.right + " , " + rect.bottom + " , " + rect.left);
//                            accessibilityNodeInfo.getBoundsInParent(rect);
//                            Log.i(TAG, "inScreen-->" + rect.top + " , " + rect.right + " , " + rect.bottom + " , " + rect.left);
//                        }
//                    } else {
//                        Log.i(TAG, "没有朋友圈");
//                    }


            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (nodeInfo != null) {
                nodeInfo.recycle();
                nodeInfo = null;
            }
        }
    }


    String description = "";
    ArrayList<Integer> topList = new ArrayList<>();
    List<AccessibilityNodeInfo> lvs;
    String mUserName = "";
    private boolean ifOnce = false;


    private void MyAccessEvent() {
        try {

            //微信UI界面的根节点，开始遍历节点
            AccessibilityNodeInfo rootNodeInfo = getRootInActiveWindow();
            if (rootNodeInfo == null) {
                return;
            }
            description = "";
            if (rootNodeInfo.getContentDescription() != null) {
                description = rootNodeInfo.getContentDescription().toString();
            }

            //自动点赞流程
            if (mUserName.equals("")) {
                //Lv
                lvs = rootNodeInfo.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/cn0");
                d("找到的Lv数量: " + lvs.size());
                //如果size不为0，证明当前在朋友圈页面下,开始执行逻辑
                if (lvs.size() != 0) {
                    //1.先记录用户名
                    List<AccessibilityNodeInfo> userNames =
                            rootNodeInfo.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/afa");
                    if (userNames.size() != 0) {
                        if (userNames.get(0).getParent() != null && userNames.get(0).getParent().getChildCount() == 4) {
                            mUserName = userNames.get(0).getText().toString();
                            if (!mUserName.equals("") && !ifOnce) {
                                d("初始化，只会执行一次");
                                d("当前的用户名:" + mUserName);
                                ifOnce = true;
                                //测试朋友圈点赞
                                test3(rootNodeInfo);
                            }
                        }
                    }
                } else {
                    ifOnce = false;
                    mUserName = "";
                }

            }


        } catch (Exception e) {
            if (e != null && e.getMessage() != null) {
                d("报错:" + e.getMessage().toString());
            }
        }
    }

    /**
     * com.tencent.mm:id/cn0
     * 朋友圈点赞 (目前实现手动滚动全部点赞)
     * 上方固定显示的名字：com.tencent.mm:id/afa
     * 下方点赞：显示id：com.tencent.mm:id/cnn
     * 每发现一个【评论按钮】，就去搜索当前同父组件下的点赞区域有没有自己的ID。
     * 如果有就不点赞，如果没有就点赞
     * 这里要改成不通过Id抓取提高稳定性
     *
     * @param rootNodeInfo
     */
    private synchronized void test3(AccessibilityNodeInfo rootNodeInfo) {
        d("当前线程:" + Thread.currentThread());
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        topList.clear();

        if (!mUserName.equals("")) {

            //测试获得评论按钮的父节点，再反推出点赞按钮
            List<AccessibilityNodeInfo> fuBtns =
                    rootNodeInfo.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/co0");

            d("fuBtns数量：" + fuBtns.size());

            if (fuBtns.size() != 0) {

                //删掉超出屏幕的fuBtn
                AccessibilityNodeInfo lastFuBtn = fuBtns.get(fuBtns.size() - 1);
                Rect lastFuBtnOutBound = new Rect();
                lastFuBtn.getBoundsInScreen(lastFuBtnOutBound);
                if (lastFuBtnOutBound.top > 22222222) {
                    fuBtns.remove(lastFuBtn);
                }

                for (int i = 0; i < fuBtns.size(); i++) {
                    AccessibilityNodeInfo fuBtn = fuBtns.get(i);
                    d("fuBtn的子节点数量:" + fuBtn.getChildCount());//3-4个
                    List<AccessibilityNodeInfo> plBtns = fuBtn.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/cj9");
                    d("从这里发现评论按钮:" + plBtns.size());

                    if (plBtns.size() == 0) {
                        if (lvs.get(0).performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD)) {
                            test3(getRootInActiveWindow());
                        }
                        return;
                    }

                    AccessibilityNodeInfo plbtn = plBtns.get(0);    //评论按钮
                    List<AccessibilityNodeInfo> zanBtns = fuBtn.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/cnn");
                    d("从这里发现点赞文字显示区域:" + zanBtns.size());
                    if (zanBtns.size() != 0) {
                        //2.如果不为空，则查找有没有自己点过赞，有则不点，没有则点
                        AccessibilityNodeInfo zanbtn = zanBtns.get(0);
                        d("点赞的人是:" + zanbtn.getText().toString());
                        if (zanbtn != null && zanbtn.getText() != null &&
                                zanbtn.getText().toString().contains(mUserName)) {
                            d("*********************这一条已经被赞过辣");
                            //判断是否需要翻页，如果当前所有页面的父节点都没点过了，就需要翻页
                            boolean ifxuyaofanye = false;
                            d("Ｏ(≧口≦)Ｏ: i=" + i + "  fuBtns.size():" + fuBtns.size());
                            if (i == fuBtns.size() - 1) {
                                ifxuyaofanye = true;
                            }
                            if (ifxuyaofanye) {
                                //滑动前检测一下是否还有没有点过的点
                                if (jianceIfLou()) {
                                    d("还有遗漏的点！！！！再检查一遍!!!!!!!!!!");
                                    test3(getRootInActiveWindow());
                                } else {
                                    if (lvs.get(0).performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD)) {
                                        test3(getRootInActiveWindow());
                                        return;
                                    }
                                }
                            }

                        } else {
                            d("**************************:自己没有赞过!");
                            //开始执行点赞流程
                            if (plBtns.size() != 0) {
                                Rect outBounds = new Rect();
                                plbtn.getBoundsInScreen(outBounds);
                                int top = outBounds.top;

                                //根据top判断如果已经点开了就不重复点开了
                                if (topList.contains(top)) {
                                    return;
                                }
                                //com.tencent.mm:id/cj5 赞
                                if (plbtn.performAction(AccessibilityNodeInfo.ACTION_CLICK)) {
                                    List<AccessibilityNodeInfo> zanlBtns = rootNodeInfo.
                                            findAccessibilityNodeInfosByViewId("com.tencent.mm:id/cj3");
                                    if (zanlBtns.size() != 0) {
                                        if (!topList.contains(top) && zanlBtns.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK)) {
                                            topList.add(top);
                                            d("topList:" + topList.toString());

                                            //判断是否需要翻页，如果当前所有页面的父节点都没点过了，就需要翻页
                                            boolean ifxuyaofanye = false;
                                            d("Ｏ(≧口≦)Ｏ: i=" + i + "  fuBtns.size():" + fuBtns.size());
                                            if (i == fuBtns.size() - 1) {
                                                ifxuyaofanye = true;
                                            }
                                            if (ifxuyaofanye) {
                                                //滑动前检测一下是否还有没有点过的点
                                                if (jianceIfLou()) {
                                                    d("还有遗漏的点！！！！再检查一遍!!!!!!!!!!");
                                                    test3(getRootInActiveWindow());
                                                } else {
                                                    if (lvs.get(0).performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD)) {
                                                        test3(getRootInActiveWindow());
                                                        return;
                                                    }
                                                }


                                            }

                                        }
                                    }
                                }
                            }
                        }

                    } else {
                        d("**************************:点赞区域为空!plBtns.size() :" + plBtns.size());

                        //开始执行点赞流程
                        if (plBtns.size() != 0) {

                            Rect outBounds = new Rect();
                            plbtn.getBoundsInScreen(outBounds);
                            int top = outBounds.top;

                            //根据top判断如果已经点开了就不重复点开了
                            if (topList.contains(top)) {
                                return;
                            }
                            //com.tencent.mm:id/cj5 赞
                            if (plbtn.performAction(AccessibilityNodeInfo.ACTION_CLICK)) {
                                List<AccessibilityNodeInfo> zanlBtns = rootNodeInfo.
                                        findAccessibilityNodeInfosByViewId("com.tencent.mm:id/cj3");
                                if (zanlBtns.size() != 0) {
                                    if (!topList.contains(top) && zanlBtns.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK)) {
                                        topList.add(top);
                                        d("topList:" + topList.toString());

                                        //判断是否需要翻页，如果当前所有页面的父节点都没点过了，就需要翻页
                                        boolean ifxuyaofanye = false;
                                        d("Ｏ(≧口≦)Ｏ: i=" + i + "  fuBtns.size():" + fuBtns.size());
                                        if (i == fuBtns.size() - 1) {
                                            ifxuyaofanye = true;
                                        }
                                        if (ifxuyaofanye) {
                                            //滑动前检测一下是否还有没有点过的点
                                            if (jianceIfLou()) {
                                                d("还有遗漏的点！！！！再检查一遍!!!!!!!!!!");
                                                test3(getRootInActiveWindow());
                                            } else {
                                                if (lvs.get(0).performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD)) {
                                                    test3(getRootInActiveWindow());
                                                    return;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

        }
    }


    private boolean jianceIfLou() {
        boolean result = false;
        List<AccessibilityNodeInfo> fuBtns =
                getRootInActiveWindow().findAccessibilityNodeInfosByViewId("com.tencent.mm:id/co0");
        d("检查的父节点数量:" + fuBtns.size());
        if (fuBtns.size() != 0) {
            for (AccessibilityNodeInfo fuBtn : fuBtns) {
                //点赞区域
                List<AccessibilityNodeInfo> zanBtns = fuBtn.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/cnn");
                d("检查的父节点的点赞区域数量:" + zanBtns.size());
                if (zanBtns.size() != 0) {
                    AccessibilityNodeInfo zanbtn = zanBtns.get(0);
                    d(" zanbtn.getText().toString():" + zanbtn.getText().toString());
                    if (zanbtn != null && zanbtn.getText() != null &&
                            zanbtn.getText().toString().contains(mUserName)) {
                        result = false;
                    } else {
                        result = true;
                    }
                } else {
                    result = true;
                }
            }
        }

        return result;
    }


    private void d(String txt) {

    }


    // 创建image
    private void createImageReader() {
        if (mImageReader == null) {
            DisplayMetrics metrics = new DisplayMetrics();
            WindowManager mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
            mWindowManager.getDefaultDisplay().getMetrics(metrics);
            mScreenDensity = metrics.densityDpi;
            mScreenWidth = metrics.widthPixels;
            mScreenHeight = metrics.heightPixels;
            mImageReader = ImageReader.newInstance(mScreenWidth, mScreenHeight, PixelFormat.RGBA_8888, 1);
        }
    }

    public static Intent getResultData() {
        return mResultData;
    }

    public static void setResultData(Intent mResultData) {
        AccessService.mResultData = mResultData;
    }

    public void startVirtual() {
        if (mMediaProjection != null) {
            virtualDisplay();
        } else {
            setUpMediaProjection();
            virtualDisplay();
        }
    }

    public void setUpMediaProjection() {
        if (mResultData == null) {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            startActivity(intent);
        } else {
            mMediaProjection = getMediaProjectionManager().getMediaProjection(Activity.RESULT_OK, mResultData);
        }
    }

    private MediaProjectionManager getMediaProjectionManager() {

        return (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
    }

    private void virtualDisplay() {
        mVirtualDisplay = mMediaProjection.createVirtualDisplay("screen-mirror",
                mScreenWidth, mScreenHeight, mScreenDensity, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
                mImageReader.getSurface(), null, null);
    }

    private void startScreenShot() {
        createImageReader();
        startVirtual();
        startCapture();
    }

    private void startCapture() {

        Image image = mImageReader.acquireLatestImage();

        if (image == null) {
            startScreenShot();
        } else {
            SaveTask mSaveTask = new SaveTask();
            //AsyncTaskCompat.executeParallel(mSaveTask, image);
            mSaveTask.execute(image);
        }
    }

    public class SaveTask extends AsyncTask<Image, Void, Bitmap> {

        @Override
        protected Bitmap doInBackground(Image... params) {

            if (params == null || params.length < 1 || params[0] == null) {

                return null;
            }

            Image image = params[0];

            int width = image.getWidth();
            int height = image.getHeight();
            final Image.Plane[] planes = image.getPlanes();
            final ByteBuffer buffer = planes[0].getBuffer();
            //每个像素的间距
            int pixelStride = planes[0].getPixelStride();
            //总的间距
            int rowStride = planes[0].getRowStride();
            int rowPadding = rowStride - pixelStride * width;
            Bitmap bitmap = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888);
            bitmap.copyPixelsFromBuffer(buffer);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height);
            image.close();
            File fileImage = null;
            if (bitmap != null) {
                try {
                    String screenShotsName = FileUtil.getScreenShotsName(getApplicationContext());
                    AccessService.SCREENSHOTFILEPATH = screenShotsName;
                    fileImage = new File(screenShotsName);
                    if (!fileImage.exists()) {
                        fileImage.createNewFile();
                    }
                    FileOutputStream out = new FileOutputStream(fileImage);
                    if (out != null) {
                        bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
                        out.flush();
                        out.close();
                        Intent media = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                        Uri contentUri = Uri.fromFile(fileImage);
                        media.setData(contentUri);
                        sendBroadcast(media);
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    fileImage = null;
                } catch (IOException e) {
                    e.printStackTrace();
                    fileImage = null;
                }
            }

            if (fileImage != null) {
                return bitmap;
            }
            return null;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            //预览图片
            if (bitmap != null) {

                ((ScreenCaptureApplication) getApplication()).setmScreenCaptureBitmap(bitmap);
                Log.e("ryze", "获取图片成功");
                Toast.makeText(AccessService.this, "", Toast.LENGTH_SHORT).show();
                // 跳转到截屏界面
                startActivity(PreviewPictureActivity.newIntent(getApplicationContext()));
            }
        }
    }


    private void tearDownMediaProjection() {
        if (mMediaProjection != null) {
            mMediaProjection.stop();
            mMediaProjection = null;
        }
    }

    private void stopVirtual() {
        if (mVirtualDisplay == null) {
            return;
        }
        mVirtualDisplay.release();
        mVirtualDisplay = null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopVirtual();
        tearDownMediaProjection();
    }
}
